using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;
using MyBlogServer.Services;
using Microsoft.AspNetCore.Authorization;

namespace MyBlogServer.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FilesController : ControllerBase
    {
        private readonly IWebHostEnvironment _environment;

        public FilesController(IWebHostEnvironment environment)
        {
            _environment = environment;
        }

        [HttpGet("{fileName}")]
        public async Task<IActionResult> GetFile(string fileName)
        {
            // 验证文件名不包含路径遍历字符
            if (fileName.Contains("..") || fileName.Contains("/") || fileName.Contains("\\"))
            {
                return BadRequest("无效的文件名");
            }

            var filePath = Path.Combine(_environment.WebRootPath, "files", fileName);

            // 检查文件是否存在
            if (!System.IO.File.Exists(filePath))
            {
                return NotFound("文件未找到");
            }

            // 获取文件扩展名
            var extension = Path.GetExtension(fileName).ToLowerInvariant();
            
            // 设置内容类型
            var contentType = GetContentType(extension);
            
            // 返回文件
            var fileBytes = await System.IO.File.ReadAllBytesAsync(filePath);
            return File(fileBytes, contentType, fileName);
        }

        private string GetContentType(string extension)
        {
            return extension switch
            {
                ".txt" => "text/plain",
                ".pdf" => "application/pdf",
                ".jpg" => "image/jpeg",
                ".jpeg" => "image/jpeg",
                ".png" => "image/png",
                ".gif" => "image/gif",
                ".zip" => "application/zip",
                ".doc" => "application/msword",
                ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                _ => "application/octet-stream"
            };
        }
    }
}